#include "../include/header.h"
bool isEnd(char* str){
	return str[0] == '0' && str[1] == '0' && str[2] == '0';
}

int main(int argc, char* argv[]){
	ARGS_CHECK(argc, 1);
	int fd_pipe  = open("pipe", O_RDONLY);
	ERROR_CHECK(fd_pipe, -1, "open");


	char filename[6] = {0};
	int ret1 = read(fd_pipe, filename, sizeof filename);
	ERROR_CHECK(ret1, -1, "read");

	int fd = open(filename, O_CREAT | O_TRUNC | O_WRONLY, 0666);
	ERROR_CHECK(fd, -1, "open");

	fd_set set;
	FD_ZERO(&set);
	while(1){
		FD_SET(fd_pipe, &set);
		int res_select = select(10, &set, NULL, NULL, NULL);
		ERROR_CHECK(res_select, -1, "select");

		if(FD_ISSET(fd_pipe, &set)){
			char frame[3 + 999] = {0};
			bzero(frame, sizeof frame);

			int ret2 = read(fd_pipe, frame, sizeof frame);
			if(ret2 == 0){
				printf("异常关闭");
				exit(-1);
			}

			if(isEnd(frame)){

				printf("写入完毕");
				exit(0);
			}
			// \n
			write(fd, frame + 3, strlen(frame + 3) - 1);
		}


	}

	return 0;
}
